<template>
  <div>
    <el-form ref="pram" :model="pram" :rules="rules" label-width="100px" @submit.native.prevent>
      <el-form-item label="单位名称" prop="unitName">
        <el-input v-model="pram.unitName" maxlength="100" placeholder="单位名称" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="pram.type" placeholder="类型" clearable style="width: 100%">
          <el-option
            v-for="(item,index) in typeList"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="排序">
        <el-input-number v-model="pram.sort" :min="0"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSubmit('pram')" v-hasPermi="['admin:department:update','admin:department:save']">{{ isCreate===0?'确定':'更新' }}</el-button>
        <el-button @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import * as departmentApi from '@/api/department.js'
import {Debounce} from '@/utils/validate'
export default {
  // name: "edit"
  components: { },
  props: {
    isCreate: {
      type: Number,
      required: true
    },
    editData: {
      type: Object,
      default: () => {
        return { rules: [] }
      }
    },
    allTypeList:{
      type: Array
    }
  },
  data() {
    return {
      constants:this.$constants,
      pram: {
        unitName: null,
        type:null,
        sort: 0,
        id: 0,
      },
      rules: {
        unitName: [{ required: true, message: '请填单位名称', trigger: ['blur', 'change'] }],
        type: [{ required: true, message: '请选择分类', trigger: ['blur', 'change'] }],
      },

      typeList:[],
    }
  },
  mounted() {
    this.initEditData()
  },
  methods: {
    close() {
      this.$emit('hideEditDialog')
    },
    initEditData() {
      this.typeList = this.allTypeList

      if (this.isCreate !== 1) return //编辑
      const { unitName, type, sort, id } = this.editData //通过list中slot-scope=“scope“，scope.$index就是该行的下标，scope.row就是该行的数据所有消息对象，有了这两个参数就可以实现编辑、删除功能（this.editData就是scope.row传入的对象参数）
      this.pram.unitName = unitName
      this.pram.type = type
      this.pram.sort = sort
      this.pram.id = id
    },
    handlerSubmit:Debounce(function(form) {
      this.$refs[form].validate(valid => {
        if (!valid) return
        if (this.isCreate === 0) {
          this.handlerSave()
        } else {
          this.handlerEdit()
        }
      })
    }),
    handlerSave() {
      departmentApi.depAdd(this.pram).then(data => {
        this.$message.success('创建单位成功')
        this.$emit('hideEditDialog')
      })
    },
    handlerEdit() {
      departmentApi.depUpdate(this.pram).then(data => {
        this.$message.success('更新单位成功')
        this.$emit('hideEditDialog')
      })
    },
  }
}
</script>

<style scoped>

</style>
